package com.hwl.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwl.server.entity.Admin;
import com.hwl.server.entity.Menu;
import com.hwl.server.mapper.MenuMapper;
import com.hwl.server.service.MenuService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author long
 * @since 2021-11-28
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<Menu> getMenusByAdminId() {
        Integer id = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();

        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        //从redis中获取菜单数据
        List<Menu> menus = (List<Menu>) valueOperations.get("menu_" + id);
        //如果为空，去数据库里获取
        if (CollectionUtils.isEmpty(menus)) {
            menus = baseMapper.getMenusByAdminId(id);
            //将数据设置到redis中
            valueOperations.set("menu_" + id, menus, 5, TimeUnit.MINUTES);
        }
        return menus;
    }

    @Override
    public List<Menu> getMenusWithRole() {
        return baseMapper.getMenusWithRole();
    }

    @Override
    public List<Menu> getAllMenus() {
        return baseMapper.getAllMenus();
    }
}
